import Cookies from 'js-cookie'
import { AuthGetCheck } from '@/utils/request'

export function setAuth (id, name, admin) {
  const auth = { id, name, admin }
  console.info('setAuth -- ', auth)
  Cookies.set('auth', auth)
}

export function checkAuth () {
  let auth = Cookies.getJSON('auth')
  if (auth === undefined || auth.id === undefined) {
    return AuthGetCheck().then(rsp => {
      const { success, profile } = rsp.data
      if (success) {
        const { userId, username, admin } = profile
        setAuth(userId, username, admin)
        return Cookies.getJSON('auth')
      }
    })
  } else {
    return new Promise((resolve, reject) => {
      resolve(auth)
    })
  }
}
